import 'dart:convert';

import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/update_terminal_play_list_status_event.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/common/common_view_model.dart';
import 'package:e_reception_flutter/ui/index/bean/update_terminal_play_list_status_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/bean/terminal_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_category_event.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_oss_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/delegate/custom_video_cache_manager.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vg_base/src/arch/base_state.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import '../../app_main.dart';

class TerminalDetailViewModel extends BasePagerViewModel<TerminalDetailListItemBean,TerminalDetailResponseBean>{


  static const String DELETE_FOLDER_API = ServerApi.BASE_URL + "app/appDelComAttPic";

  static const String DELETE_FOVERVER_FOLDER_API = ServerApi.BASE_URL + "app/appDelComPic";

  static const String UPDATE_NAME_FOLDER_API =ServerApi.BASE_URL + "app/appUpdatePicname";

  static const String REPEAT_PLAY_API =ServerApi.BASE_URL + "app/appStopPicByhsn";

  ///不喜欢/删除合成海报
  static const String DELETE_COMPOSE_POSTER_API =ServerApi.BASE_URL + "app/appDelComAttPicCompose";

  final String hsn;

  ValueNotifier<HsnMapBean> hsnInfoValueNotifier;
  ValueNotifier<TerminalDetailDataBean> picListValueNotifier;
  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;

  TerminalDetailViewModel(BaseState<StatefulWidget> state,this.hsn) : super(state){
    hsnInfoValueNotifier = ValueNotifier(null);
    picListValueNotifier = ValueNotifier(null);
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
  }

  @override
  void onDisposed() {
    hsnInfoValueNotifier?.dispose();
    picListValueNotifier?.dispose();
    super.onDisposed();
  }

  void getTerminalWithCache(){
    String cacheKey = NetApi.TERMINAL_PLAY_LIST_API + (UserRepository.getInstance().getCacheKeySuffix()??"")
        + (hsn??"");
    print("cacheKey:" + cacheKey);
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        Map map = json.decode(jsonStr);
        TerminalDetailResponseBean bean = TerminalDetailResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            hsnInfoValueNotifier?.value = bean.data?.hsnMap;
            picListValueNotifier?.value = bean.data;
          }
        }
      }
    });
    getTerminalPlayList();
  }

  ///获取详情
  void getTerminalPlayList(){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    String cacheKey = NetApi.TERMINAL_PLAY_LIST_API + (UserRepository.getInstance().getCacheKeySuffix()??"")
        + (hsn??"");
    VgHttpUtils.get(NetApi.TERMINAL_PLAY_LIST_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
    },callback: BaseCallback(
        onSuccess: (val){
          TerminalDetailResponseBean vo =
          TerminalDetailResponseBean.fromMap(val);
          loading(false);
          if(!isStateDisposed){
            if(vo == null || vo.data == null || vo.data.list == null || vo.data.list.length < 1){
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }else{
              statusTypeValueNotifier?.value = null;
            }
            hsnInfoValueNotifier?.value = vo.data?.hsnMap;
            picListValueNotifier?.value = vo.data;
          }
          if(vo != null){
            SharePreferenceUtil.putString(cacheKey, json.encode(vo));
          }
        },
        onError: (msg){
          loading(false);
          toast(msg);
          statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
        }
    ));
  }

  ///重复播放/取消重复播放资源 picid暂停图片id，取消传空 stopflg01 暂停 02取消暂停
  void repeatPlay(BuildContext context,String picid, String stopflg, String id){
    if(StringUtils.isEmpty(picid)){
      return;
    }
//    VgHudUtils.show(context,"");
    VgHttpUtils.get(REPEAT_PLAY_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "picid": picid ?? "",
      "stopflg": stopflg ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
//          VgToastUtils.toast(context, "处理成功");
          refreshMultiPage();
          //通知首页更新
          VgEventBus.global.send(MediaLibraryRefreshEven());
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///删除资源
  void deleteFolder(BuildContext context,String picid, {String currentHsn}){
    if(StringUtils.isEmpty(picid)){
      return;
    }
    VgHudUtils.show(context,"删除中");
    VgHttpUtils.get(DELETE_FOLDER_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":currentHsn??hsn,
      "picid": picid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          refreshMultiPage();
          //通知首页更新
          VgEventBus.global.send(MediaLibraryRefreshEven());
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }

  //删除合成海报
  void deleteComposePoster(BuildContext context, String hsn, String id, String intoflg, String splpicurl){
    VgHudUtils.show(context,"删除中");
    VgHttpUtils.get(DELETE_COMPOSE_POSTER_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "id": id ?? "",
      "intoflg": intoflg ?? "",
      "splpicurl": splpicurl ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          refreshMultiPage();
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  //删除今日推送海报
  void deleteTodayPushPoster(BuildContext context, String hsn, String id){
    String companyid = UserRepository.getInstance().getCompanyId();
    VgHudUtils.show(context,"删除中");
    VgHttpUtils.get(NetApi.DELETE_TODAY_PUSH_POSTER,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "id": id ?? "",
      "companyid": companyid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          refreshMultiPage();
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  //删除指示牌
  void deleteTerminalBuildingIndex(BuildContext context, String hsn, String id){
    VgHudUtils.show(context,"删除中");
    VgHttpUtils.get(NetApi.DELETE_TERMINAL_BUILDING_INDEX,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          refreshMultiPage();
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  ///删除智能家居
  void deleteSmartHome(BuildContext context, String shid, String removeHsns){
    if(StringUtils.isEmpty(shid)){
      return;
    }
    VgHudUtils.show(context, "设置中");
    VgHttpUtils.post(NetApi.SMART_HOME_SET_TERMINAL, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "shid": shid??"",
      "hsns":"",
      "removeHsns":removeHsns ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, "删除成功");
          VgEventBus.global.send(new RefreshSmartHomeCategoryEvent());
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
          refreshMultiPage();
          loading(false);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  //永久删除指示牌
  void foreverDeleteTerminalBuildingIndex(BuildContext context, String comwid){
    VgHudUtils.show(context,"删除中");
    VgHttpUtils.get(NetApi.FOREVER_DELETE_TERMINAL_BUILDING_INDEX,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "comwid": comwid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除成功");
          refreshMultiPage();
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgHudUtils.hide(context);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }


  ///取消已选的资源
  void cancelFolder(BuildContext context,String picid){
    if(StringUtils.isEmpty(picid)){
      return;
    }
    VgHudUtils.show(context,"取消中");
    VgHttpUtils.get(DELETE_FOLDER_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn":hsn,
      "picid": picid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "取消成功");
          refreshMultiPage();
          RouterUtils.pop(context);
          //通知首页更新
          VgEventBus.global.send(MediaLibraryRefreshEven());
          getUpdateTerminalPlayListStatus(hsn);
        },
        onError: (msg){
          VgHudUtils.hide(context);

          VgToastUtils.toast(context, msg);
        }
    ));
  }

  ///删除视频文件
  void deleteVodVideoFile(String videoId){
    if(StringUtils.isEmpty(videoId)){
      return;
    }
    VgHttpUtils.get(NetApi.DELETE_VOD_VIDEO_FILE,params: {
      "videoid":videoId,
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));

  }

  ///删除资源
  void deleteForeverFolder(BuildContext context,String picid, String videoId, String picurl, String videoUrl){
    if(StringUtils.isEmpty(picid)){
      return;
    }
    VgHudUtils.show(context,"删除中");
    VgHttpUtils.get(DELETE_FOVERVER_FOLDER_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid": picid ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          //删除服务端图片文件
          VgOssUtils.deleteObject(picurl);
          //删除服务端视频文件
          if(StringUtils.isNotEmpty(videoId)){
            deleteVodVideoFile(videoId);
          }
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, "删除文件成功");
          //删除本地视频缓存
          if(StringUtils.isNotEmpty(videoUrl)){
            CustomVideoCacheManager().removeFile(videoUrl);
          }
          refreshMultiPage();
          //通知首页更新
          VgEventBus.global.send(MediaLibraryRefreshEven());
          getUpdateTerminalPlayListStatus(hsn);
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }
  ///查询终端获取资源是否成功
  void getUpdateTerminalPlayListStatus(String hsn){
    String authId = UserRepository.getInstance().authId;
    if(StringUtils.isEmpty(authId)){
      return;
    }
    ///网络请求
    VgHttpUtils.get(NetApi.UPDATE_TERMINAL_PLAY_LIST_STATUS_API,params: {
      "authId":authId ?? "",
      "hsn":hsn ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          UpdateTerminalPlayListStatusBean bean = UpdateTerminalPlayListStatusBean.fromMap(val);
          if(bean != null){
            VgEventBus.global.send(new UpdateTerminalPlayListStatusEvent(bean?.data?.obtainflg??"", hsn));
          }
        },
        onError: (msg){
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }
  ///重命名
  void updateFolderName(BuildContext context,String picid,String name,VoidCallback onPop){
    if(StringUtils.isEmpty(picid)){
      return;
    }
    if(StringUtils.isEmpty(name)){
      VgToastUtils.toast(context, "文件名不能为空");
      return;
    }
    VgHudUtils.show(context,"重命名中");
    VgHttpUtils.get(UPDATE_NAME_FOLDER_API,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "picid": picid ?? "",
      "picname": name ?? ""
    },callback: BaseCallback(
        onSuccess: (val){
          VgHudUtils.hide(context);
          onPop?.call();
          VgToastUtils.toast(context, "重命名成功");
          refreshMultiPage();
          //通知首页更新
          VgEventBus.global.send(MediaLibraryRefreshEven());
        },
        onError: (msg){
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }
    ));
  }

  @override
  Map<String, dynamic> getQuery(int page) {
    Map<String, dynamic> map = {
      "authId": UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
    };
    return map;
  }

  @override
  String getRequestMethod() {
    return HttpUtils.GET;
  }

  @override
  String getUrl() {
    return NetApi.TERMINAL_PLAY_LIST_API;
  }

  @override
  TerminalDetailResponseBean parseData(VgHttpResponse resp) {
    TerminalDetailResponseBean vo =
    TerminalDetailResponseBean.fromMap(resp?.data);
    loading(false);
    hsnInfoValueNotifier?.value = vo.data?.hsnMap;
    return vo;
  }

  @override
  String getBodyData(int page) {
    return null;
  }
}